<!DOCTYPE html>
<html lang="en">
<head><!-- hexo injector head_begin start -->
        <link rel="preconnect" href="https://blog.fantasyke.cn/picx-images-hosting" crossorigin=""><!-- hexo injector head_begin end -->
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/uploads/avatar.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/uploads/avatar.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="google-site-verification" content="0qBBGdG7vYORyT5XLZRUqQZ_y5kKYhgyUwNqjSIImg0">
  <meta name="msvalidate.01" content="63C90D0EC3DA6C31FD109132B7BEF502">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Zen+Maru+Gothic:300,300italic,400,400italic,700,700italic%7CZCOOL+XiaoWei:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" integrity="sha256-5eIC48iZUHmSlSUz9XtjRyK2mzQkHScZY1WdMaoz74E=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.31/fancybox/fancybox.css" integrity="sha256-gkQVf8UKZgQ0HyuxL/VnacadJ+D2Kox2TCEBuNQg5+w=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.fantasyke.cn","root":"/","images":"/images","scheme":"Mist","darkmode":false,"version":"8.21.1","exturl":true,"sidebar":{"position":"right","width_expanded":350,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":null},"fold":{"enable":true,"height":500},"bookmark":{"enable":true,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":true,"nav":{"gitalk":{"text":"gitalk","order":-1}},"activeClass":"gitalk"},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="消息是如何保障100%的投递成功 生产端的可靠性投递 具体解决方案">
<meta property="og:type" content="article">
<meta property="og:title" content="RabbitMQ进阶">
<meta property="og:url" content="https://blog.fantasyke.cn/posts/59211/index.html">
<meta property="og:site_name" content="Fantasy&#39;Ke Blog">
<meta property="og:description" content="消息是如何保障100%的投递成功 生产端的可靠性投递 具体解决方案">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://fantasy-ke.github.io/picx-images-hosting/rabbitMQ/image.syyxe08gy.webp">
<meta property="og:image" content="https://fantasy-ke.github.io/picx-images-hosting/rabbitMQ/image.58he2nd6n4.webp">
<meta property="og:image" content="https://fantasy-ke.github.io/picx-images-hosting/rabbitMQ/image.175eo9a2kr.webp">
<meta property="og:image" content="https://fantasy-ke.github.io/picx-images-hosting/rabbitMQ/image.3yegwb5uo1.webp">
<meta property="article:published_time" content="2023-05-29T01:32:00.000Z">
<meta property="article:modified_time" content="2024-12-17T06:36:35.391Z">
<meta property="article:author" content="Fantasy-ke">
<meta property="article:tag" content="消息队列">
<meta property="article:tag" content="RabbitMQ">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fantasy-ke.github.io/picx-images-hosting/rabbitMQ/image.syyxe08gy.webp">


<link rel="canonical" href="https://blog.fantasyke.cn/posts/59211/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"en","comments":true,"permalink":"https://blog.fantasyke.cn/posts/59211/","path":"posts/59211/","title":"RabbitMQ进阶"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>RabbitMQ进阶 | Fantasy'Ke Blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<link rel="alternate" href="/atom.xml" title="Fantasy'Ke Blog" type="application/atom+xml">
<style>.darkmode--activated{--body-bg-color:#282828;--content-bg-color:#333;--card-bg-color:#555;--text-color:#ccc;--blockquote-color:#bbb;--link-color:#ccc;--link-hover-color:#eee;--brand-color:#ddd;--brand-hover-color:#ddd;--table-row-odd-bg-color:#282828;--table-row-hover-bg-color:#363636;--menu-item-bg-color:#555;--btn-default-bg:#222;--btn-default-color:#ccc;--btn-default-border-color:#555;--btn-default-hover-bg:#666;--btn-default-hover-color:#ccc;--btn-default-hover-border-color:#666;--highlight-background:#282b2e;--highlight-foreground:#a9b7c6;--highlight-gutter-background:#34393d;--highlight-gutter-foreground:#9ca9b6}.darkmode--activated img{opacity:.75}.darkmode--activated img:hover{opacity:.9}.darkmode--activated code{color:#69dbdc;background:0 0}button.darkmode-toggle{z-index:9999}.darkmode-ignore,img{display:flex!important}.beian img{display:inline-block!important}</style></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Fantasy'Ke Blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="Search" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a></li><li class="menu-item menu-item-photos"><a href="/photos/" rel="section"><i class="fas fa-camera-retro fa-fw"></i>photos</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="Searching..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">1.</span> <span class="nav-text"> 消息是如何保障100%的投递成功</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-2"><span class="nav-number">1.1.</span> <span class="nav-text"> 生产端的可靠性投递</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-3"><span class="nav-number">1.2.</span> <span class="nav-text"> 具体解决方案</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-4"><span class="nav-number">2.</span> <span class="nav-text"> 幂等性&#x2F;怎么避免重复消费</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-5"><span class="nav-number">2.1.</span> <span class="nav-text"> 消费端-幂等性保障</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-6"><span class="nav-number">2.2.</span> <span class="nav-text"> 具体解决方案</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-7"><span class="nav-number">3.</span> <span class="nav-text"> Confirm确认消息</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-8"><span class="nav-number">3.1.</span> <span class="nav-text"> 代码示例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-9"><span class="nav-number">3.1.1.</span> <span class="nav-text"> 创建项目</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-10"><span class="nav-number">3.1.2.</span> <span class="nav-text"> 具体代码</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-11"><span class="nav-number">4.</span> <span class="nav-text"> Return返回消息</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-12"><span class="nav-number">4.1.</span> <span class="nav-text"> 代码示例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-13"><span class="nav-number">4.1.1.</span> <span class="nav-text"> 创建项目</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-14"><span class="nav-number">4.1.2.</span> <span class="nav-text"> 具体代码</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-15"><span class="nav-number">5.</span> <span class="nav-text"> 自定义消费者</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-16"><span class="nav-number">5.1.</span> <span class="nav-text"> 代码示例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-17"><span class="nav-number">5.1.1.</span> <span class="nav-text"> 创建项目</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-18"><span class="nav-number">5.1.2.</span> <span class="nav-text"> 具体代码</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-19"><span class="nav-number">6.</span> <span class="nav-text"> 消息的限流</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-20"><span class="nav-number">6.1.</span> <span class="nav-text"> 代码示例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-21"><span class="nav-number">6.1.1.</span> <span class="nav-text"> 创建项目</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#-22"><span class="nav-number">6.1.1.1.</span> <span class="nav-text"> 具体代码</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-23"><span class="nav-number">7.</span> <span class="nav-text"> 消息的ACK与重回队列</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-24"><span class="nav-number">7.1.</span> <span class="nav-text"> 消费端的手工ACK和NACK</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-25"><span class="nav-number">7.2.</span> <span class="nav-text"> 消费端的重回队列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-26"><span class="nav-number">7.3.</span> <span class="nav-text"> 代码示例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-27"><span class="nav-number">7.3.1.</span> <span class="nav-text"> 创建项目</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-28"><span class="nav-number">8.</span> <span class="nav-text"> TTL消息</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-29"><span class="nav-number">9.</span> <span class="nav-text"> DLX–死信队列(Dead-Letter-Exchange)</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-30"><span class="nav-number">10.</span> <span class="nav-text"> ASP.NET Core做消费者</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-31"><span class="nav-number">10.1.</span> <span class="nav-text"> 代码示例</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Fantasy-ke"
      src="/uploads/avatar.png">
  <p class="site-author-name" itemprop="name">Fantasy-ke</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">36</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2ZhbnRhc3kta2U=" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;fantasy-ke"><i class="fab fa-github fa-fw"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly94LmNvbS9BX0RyZWFtZXJfSGFyZA==" title="Twitter → https:&#x2F;&#x2F;x.com&#x2F;A_Dreamer_Hard"><i class="fab fa-twitter fa-fw"></i>Twitter</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly93d3cueW91dHViZS5jb20vQCVFNSU5MSVBOCVFNiVBMiVBNi16OWk=" title="YouTube → https:&#x2F;&#x2F;www.youtube.com&#x2F;@%E5%91%A8%E6%A2%A6-z9i"><i class="fab fa-youtube fa-fw"></i>YouTube</span>
      </span>
  </div>
<div class="cc-license animated" itemprop="sponsor">
  <a href="https://www.netlify.com" class="cc-opacity" title="Deploy with Netlify → https://www.netlify.com" target="_blank"><img width="80" src="https://www.netlify.com/img/global/badges/netlify-dark.svg" alt="Netlify"></a>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css">
<div id="aplayer" style="position:relative;left;0;bottom:0;"></div>
<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/color-thief-don@2.0.2/src/color-thief.js"></script>
<script>
  const ap = new APlayer({
    container: document.getElementById('aplayer'),
    autoplay: false, //自动播放
    listFolded: true, //播放列表默认折叠
    listMaxHeight: 90, //播放列表最大高度
    order: 'list', //音频循环顺序, 可选值: 'list', 'random'
    loop: 'all', //音频循环播放, 可选值: 'all', 'one', 'none'
    theme: '#e9e9e9', //切换音频时的主题色，优先级低于audio.theme
    preload: 'none', //音频预加载，可选值: 'none', 'metadata', 'auto'
    mutex: true, //互斥，阻止多个播放器同时播放，当前播放器播放时暂停其他播放器
    lrcType: 3, //歌词格式，可选值：3（LRC文件歌词格式），1（JS字符串歌词格式）
    volume: 0.7, //默认音量，请注意播放器会记忆用户设置，用户手动设置音量后默认音量即失效
    fixed: false, //吸底模式（fixed:true），迷你模式（mini:true），普通模式（注释此行或者设置fixed:false）
    audio: [{
        name: '平凡之路',
        artist: '朴树',
        lrc: '/downloads/lrc/平凡之路-朴树.lrc',
        cover: 'http://p2.music.126.net/W_5XiCv3rGS1-J7EXpHSCQ==/18885211718782327.jpg?param=300x300',
        url: 'http://ws.stream.qqmusic.qq.com/C4000007nRJ74eQsF6.m4a?guid=942726817&vkey=64755357C5716983BEECE2981FEC3954F0DD03E7630EFF769D9C40C31F50D53E7D260CB63E22CE8F954B1144083716A1BABFC2093F8F1C14&uin=&fromtag=120032'
      },
      {
        name: '后会无期',
        artist: '徐良,汪苏泷',
        lrc: '/downloads/lrc/后会无期-G.E.M.邓紫棋.lrc',
        cover: 'http://p1.music.126.net/vpvPajo3kn88nHc7jUjeWQ==/5974746185758035.jpg?param=300x300',
        url: 'http://ws.stream.qqmusic.qq.com/C400004ECnYg0QNchK.m4a?guid=893251117&vkey=D9DCBB8C4A4CAF8550E97A2A574DE1231DFDD8BC0989CC724742C7B9831C4108E0A805A46E0F2B2A556228467C146B9C312E3E8B498614C7&uin=&fromtag=120032'
      }
    ]
  });

  // 实现切换音频时，根据音频的封面图片自适应主题色
  const colorThief = new ColorThief();
  const setTheme = (index) => {
    if (!ap.list.audios[index].theme) {
      colorThief.getColorAsync(ap.list.audios[index].cover, function(color) {
        ap.theme(`rgb(${color[0]}, ${color[1]}, ${color[2]})`, index);
      });
    }
  };
  setTheme(ap.list.index);
  ap.on('listswitch', (data) => {
    setTheme(data.index);
  });
</script>



        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          Links
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9mYW50YXN5LWtlLmdpdGh1Yi5pbw==" title="https:&#x2F;&#x2F;fantasy-ke.github.io">SunBlog</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9mYW50YXN5LWtlLmdpdGh1Yi5pbw==" title="https:&#x2F;&#x2F;fantasy-ke.github.io">做梦的努力者</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0ZhbnRhc3ktS2U=" title="https:&#x2F;&#x2F;github.com&#x2F;Fantasy-Ke">github</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9naXRlZS5jb20vZmFudGFzeV9rZQ==" title="https:&#x2F;&#x2F;gitee.com&#x2F;fantasy_ke">gitee</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly93d3cuY25ibG9ncy5jb20vZmFudGFzeS1rZQ==" title="https:&#x2F;&#x2F;www.cnblogs.com&#x2F;fantasy-ke">我的园子</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9hYnAuaW8v" title="https:&#x2F;&#x2F;abp.io&#x2F;">abp</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9hYnAuaW8vZG9jcy9sYXRlc3Qv" title="https:&#x2F;&#x2F;abp.io&#x2F;docs&#x2F;latest&#x2F;">abp doc</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9ibG9ncy5tYXNhc3RhY2suY29tLw==" title="https:&#x2F;&#x2F;blogs.masastack.com&#x2F;">masa blog</span>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        <div class="sidebar-inner sidebar-post-related">
          <div class="animated">
              <div class="links-of-blogroll-title"><i class="fa fa-signs-post fa-fw"></i>
    Related Posts
  </div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/posts/34332/" rel="bookmark">
        <time class="popular-posts-time">2023-06-28</time>
        <br>
      gRPC in ASP.NET Core
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/" rel="bookmark">
      
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/posts/33842/" rel="bookmark">
        <time class="popular-posts-time">2023-05-26</time>
        <br>
      RabbitMQ基础
      </a>
    </li>
  </ul>

          </div>
        </div>
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="en">
    <link itemprop="mainEntityOfPage" href="https://blog.fantasyke.cn/posts/59211/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/uploads/avatar.png">
      <meta itemprop="name" content="Fantasy-ke">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Fantasy'Ke Blog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="RabbitMQ进阶 | Fantasy'Ke Blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          RabbitMQ进阶
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2023-05-29 09:32:00" itemprop="dateCreated datePublished" datetime="2023-05-29T09:32:00+08:00">2023-05-29</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2024-12-17 14:36:35" itemprop="dateModified" datetime="2024-12-17T14:36:35+08:00">2024-12-17</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%9D%82%E4%B8%83%E6%9D%82%E5%85%AB%E7%9A%84%E7%A0%96/" itemprop="url" rel="index"><span itemprop="name">杂七杂八的砖</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="Views" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">Views: </span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="Word count in article">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">Word count in article: </span>
      <span>3.5k</span>
    </span>
    <span class="post-meta-item" title="Reading time">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">Reading time &asymp;</span>
      <span>13 mins.</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><!-- more -->
<!-- - [消息是如何保障100%的投递成功](#消息是如何保障100的投递成功)
  - [生产端的可靠性投递](#生产端的可靠性投递)
- [幂等性/怎么避免重复消费](#幂等性怎么避免重复消费)
  - [消费端-幂等性保障](#消费端-幂等性保障)
  - [具体解决方案](#具体解决方案)
- [Confirm确认消息](#confirm确认消息)
  - [代码示例](#代码示例)
    - [创建项目](#创建项目)
    - [具体代码](#具体代码)
- [Return返回消息](#return返回消息)
  - [代码示例](#代码示例-1)
    - [创建项目](#创建项目-1)
    - [具体代码](#具体代码-1)
- [自定义消费者](#自定义消费者)
  - [代码示例](#代码示例-2)
    - [创建项目](#创建项目-2)
    - [具体代码](#具体代码-2)
- [消息的限流](#消息的限流)
  - [代码示例](#代码示例-3)
    - [创建项目](#创建项目-3)
      - [具体代码](#具体代码-3)
- [消息的ACK与重回队列](#消息的ack与重回队列)
  - [消费端的手工ACK和NACK](#消费端的手工ack和nack)
  - [消费端的重回队列](#消费端的重回队列)
  - [代码示例](#代码示例-4)
    - [创建项目](#创建项目-4)
- [TTL消息](#ttl消息)
- [DLX–死信队列(Dead-Letter-Exchange)](#dlx死信队列dead-letter-exchange)
- [ASP.NET Core做消费者](#aspnet-core做消费者)
  - [代码示例](#代码示例-5) -->
<!-- > 源码：[https://github.com/xiejiamiao/AllSamples](https://github.com/xiejiamiao/AllSamples) -->
<h1 id=""><a class="markdownIt-Anchor" href="#"></a> <a href="#%E6%B6%88%E6%81%AF%E6%98%AF%E5%A6%82%E4%BD%95%E4%BF%9D%E9%9A%9C100-%E7%9A%84%E6%8A%95%E9%80%92%E6%88%90%E5%8A%9F" title="消息是如何保障100%的投递成功"></a>消息是如何保障100%的投递成功</h1>
<h2 id="-2"><a class="markdownIt-Anchor" href="#-2"></a> <a href="#%E7%94%9F%E4%BA%A7%E7%AB%AF%E7%9A%84%E5%8F%AF%E9%9D%A0%E6%80%A7%E6%8A%95%E9%80%92" title="生产端的可靠性投递"></a>生产端的可靠性投递</h2>
<ul>
<li>
<p>保障消息的成功发出</p>
</li>
<li>
<p>保障MQ节点的成功接受</p>
</li>
<li>
<p>发送端收到MQ节点(Broker)确认应答</p>
</li>
<li>
<p>完善的消息进行补偿机制</p>
<h2 id="-3"><a class="markdownIt-Anchor" href="#-3"></a> <a href="#%E5%85%B7%E4%BD%93%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88" title="具体解决方案"></a>具体解决方案</h2>
</li>
<li>
<p>消息落库，对消息状态进行达标。即在发送消息的时候将消息持久化到数据库中，然后进行状态维护</p>
<p><img src="https://fantasy-ke.github.io/picx-images-hosting/rabbitMQ/image.syyxe08gy.webp" alt="消息落库.png" /></p>
<p>缺陷：需要对消息做持久化，这样在遇到高并发的场景，数据库压力大</p>
</li>
<li>
<p>消息的延迟投递，做二次确认，回调检查</p>
<p><img src="https://fantasy-ke.github.io/picx-images-hosting/rabbitMQ/image.58he2nd6n4.webp" alt="消息延迟投递.png" /></p>
</li>
</ul>
<h1 id="-4"><a class="markdownIt-Anchor" href="#-4"></a> <a href="#%E5%B9%82%E7%AD%89%E6%80%A7-%E6%80%8E%E4%B9%88%E9%81%BF%E5%85%8D%E9%87%8D%E5%A4%8D%E6%B6%88%E8%B4%B9" title="幂等性/怎么避免重复消费"></a>幂等性/怎么避免重复消费</h1>
<p>幂等性：通俗的讲就是一个操作不管做多少次，结果永远都一样</p>
<h2 id="-5"><a class="markdownIt-Anchor" href="#-5"></a> <a href="#%E6%B6%88%E8%B4%B9%E7%AB%AF-%E5%B9%82%E7%AD%89%E6%80%A7%E4%BF%9D%E9%9A%9C" title="消费端-幂等性保障"></a>消费端-幂等性保障</h2>
<p>消费端实现幂等性，就意味着消费端永远不会消费多次，即使消费端收到多条一样的消息</p>
<h2 id="-6"><a class="markdownIt-Anchor" href="#-6"></a> <a href="#%E5%85%B7%E4%BD%93%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88-1" title="具体解决方案"></a>具体解决方案</h2>
<ul>
<li>
<p><code>唯一ID+指纹码</code>机制</p>
<ul>
<li>唯一ID+指纹码 机制，利用数据库主键去重</li>
<li>SELECT COUNT(1) FROM T _ORDER WHERE ID=(唯一ID+指纹码)</li>
<li>好处：实现简单</li>
<li>坏处：高并发下有数据库写入的性能瓶颈</li>
<li>解决方案：跟进ID进行分库分表进行算法路由</li>
</ul>
</li>
<li>
<p>利用Redis的原子性去实现</p>
<ul>
<li>数据是否需要进行数据落库，如果落库的话，关键解决的问题是数据库和缓存如何做到原子性</li>
<li>如果数据不落库，那么都存在缓存中，如何设置定时同步的策略</li>
</ul>
</li>
</ul>
<h1 id="-7"><a class="markdownIt-Anchor" href="#-7"></a> <a href="#Confirm%E7%A1%AE%E8%AE%A4%E6%B6%88%E6%81%AF" title="Confirm确认消息"></a>Confirm确认消息</h1>
<ul>
<li>消息的确定，是指生产者投递消息后，如果Broker收到消息，则会给生产者一个应答</li>
<li>生产者进行接受应答，用来确定这条消息是否正常的发送给Broker，这种方法也是消息的可靠性投递的核心保障</li>
</ul>
<p><img src="https://fantasy-ke.github.io/picx-images-hosting/rabbitMQ/image.175eo9a2kr.webp" alt="Confirm机制流程图.png" /></p>
<h2 id="-8"><a class="markdownIt-Anchor" href="#-8"></a> <a href="#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B" title="代码示例"></a>代码示例</h2>
<h3 id="-9"><a class="markdownIt-Anchor" href="#-9"></a> <a href="#%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE" title="创建项目"></a>创建项目</h3>
<p>创建两个控制台应用程序</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ComfirmSample.Consumer  </span><br><span class="line">ComfirmSample.Producer  </span><br></pre></td></tr></table></figure>
<p>再分别通过nuget引入<code>RabbitMQ.Client</code></p>
<h3 id="-10"><a class="markdownIt-Anchor" href="#-10"></a> <a href="#%E5%85%B7%E4%BD%93%E4%BB%A3%E7%A0%81" title="具体代码"></a>具体代码</h3>
<p>ComfirmSample.Producer</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Text;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">ComfirmSample.Producer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">  <span class="keyword">class</span> <span class="title">Program</span>  </span><br><span class="line">  &#123;  </span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>[] args</span>)</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">      Console.WriteLine(<span class="string">&quot;\*\*\*\*\*\* Confirm Sample Producer \*\*\*\*\*\*&quot;</span>);  </span><br><span class="line">        </span><br><span class="line">      <span class="keyword">var</span> connectionFactory = <span class="keyword">new</span> ConnectionFactory()  </span><br><span class="line">      &#123;  </span><br><span class="line">        HostName = <span class="string">&quot;127.0.0.1&quot;</span>,  </span><br><span class="line">        Port = <span class="number">5672</span>,  </span><br><span class="line">        UserName = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">        Password = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">        VirtualHost = <span class="string">&quot;/&quot;</span>  </span><br><span class="line">      &#125;;  </span><br><span class="line">        </span><br><span class="line">      <span class="keyword">using</span> <span class="keyword">var</span> connection = connectionFactory.CreateConnection();  </span><br><span class="line">      <span class="keyword">using</span> <span class="keyword">var</span> channel = connection.CreateModel();  </span><br><span class="line">        </span><br><span class="line">      <span class="comment">// 指定消息投递模式=Confirm  </span></span><br><span class="line">      channel.ConfirmSelect();  </span><br><span class="line">        </span><br><span class="line">      <span class="keyword">var</span> exchangeName = <span class="string">&quot;test _confirm _exchange&quot;</span>;  </span><br><span class="line">      <span class="keyword">var</span> routingKey = <span class="string">&quot;confirm.save&quot;</span>;  </span><br><span class="line">        </span><br><span class="line">      <span class="keyword">var</span> message = <span class="string">&quot;Hello RabbitMQ For Confirm Message&quot;</span>;  </span><br><span class="line">      <span class="keyword">var</span> body = Encoding.UTF8.GetBytes(message);  </span><br><span class="line">        </span><br><span class="line">      channel.BasicPublish(exchangeName, routingKey, <span class="literal">null</span>, body);  </span><br><span class="line">        </span><br><span class="line">      <span class="comment">// 添加确认监听  </span></span><br><span class="line">      channel.BasicAcks += (sender, ea) =&gt;  </span><br><span class="line">      &#123;  </span><br><span class="line">        Console.WriteLine(<span class="string">$&quot;消息确认被MQ收到  DeliveryTag=<span class="subst">&#123;ea.DeliveryTag&#125;</span>&quot;</span>);  </span><br><span class="line">      &#125;;  </span><br><span class="line">      <span class="comment">// no ack-ed  </span></span><br><span class="line">      channel.BasicNacks += (sender, ea) =&gt;  </span><br><span class="line">      &#123;  </span><br><span class="line">        Console.WriteLine(<span class="string">$&quot;消息发送失败  DeliveryTag=<span class="subst">&#123;ea.DeliveryTag&#125;</span>&quot;</span>);  </span><br><span class="line">      &#125;;  </span><br><span class="line">        </span><br><span class="line">      Console.WriteLine(<span class="string">&quot;消息发送完成&quot;</span>);  </span><br><span class="line">      Console.WriteLine(<span class="string">&quot;输入回车退出...&quot;</span>);  </span><br><span class="line">      Console.ReadLine();  </span><br><span class="line">    &#125;  </span><br><span class="line">  &#125;  </span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<p>ComfirmSample.Consumer</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Text;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client.Events;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">ComfirmSample.Consumer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">  <span class="keyword">class</span> <span class="title">Program</span>  </span><br><span class="line">  &#123;  </span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>[] args</span>)</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">      Console.WriteLine(<span class="string">&quot;\*\*\*\*\*\* Confirm Sample Consumer \*\*\*\*\*\*&quot;</span>);  </span><br><span class="line">        </span><br><span class="line">      <span class="keyword">var</span> connectionFactory = <span class="keyword">new</span> ConnectionFactory()  </span><br><span class="line">      &#123;  </span><br><span class="line">        HostName = <span class="string">&quot;127.0.0.1&quot;</span>,  </span><br><span class="line">        Port = <span class="number">5672</span>,  </span><br><span class="line">        UserName = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">        Password = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">        VirtualHost = <span class="string">&quot;/&quot;</span>  </span><br><span class="line">      &#125;;  </span><br><span class="line">        </span><br><span class="line">      <span class="keyword">using</span> <span class="keyword">var</span> connection = connectionFactory.CreateConnection();  </span><br><span class="line">      <span class="keyword">using</span> <span class="keyword">var</span> channel = connection.CreateModel();  </span><br><span class="line">        </span><br><span class="line">      <span class="keyword">var</span> exchangeName = <span class="string">&quot;test _confirm _exchange&quot;</span>;  </span><br><span class="line">      <span class="keyword">var</span> queueName = <span class="string">&quot;test _confirm _queue&quot;</span>;  </span><br><span class="line">      <span class="keyword">var</span> routingKey = <span class="string">&quot;confirm.save&quot;</span>;  </span><br><span class="line">        </span><br><span class="line">      channel.ExchangeDeclare(exchangeName,ExchangeType.Direct,<span class="literal">true</span>,<span class="literal">false</span>,<span class="literal">null</span>);  </span><br><span class="line">      channel.QueueDeclare(queueName, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);  </span><br><span class="line">      channel.QueueBind(queueName, exchangeName, routingKey, <span class="literal">null</span>);  </span><br><span class="line">        </span><br><span class="line">      <span class="keyword">var</span> consumer = <span class="keyword">new</span> EventingBasicConsumer(channel);  </span><br><span class="line">      channel.BasicConsume(queueName, <span class="literal">true</span>, consumer);  </span><br><span class="line">      consumer.Received += (model, ea) =&gt;  </span><br><span class="line">      &#123;  </span><br><span class="line">        <span class="keyword">var</span> body = ea.Body;  </span><br><span class="line">        <span class="keyword">var</span> message = Encoding.UTF8.GetString(body.ToArray());  </span><br><span class="line">        Console.WriteLine(<span class="string">$&quot;接收到消息：<span class="subst">&#123;message&#125;</span>&quot;</span>);  </span><br><span class="line">      &#125;;  </span><br><span class="line">        </span><br><span class="line">      Console.WriteLine(<span class="string">&quot;输入回车退出...&quot;</span>);  </span><br><span class="line">      Console.ReadLine();  </span><br><span class="line">    &#125;  </span><br><span class="line">  &#125;  </span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<h1 id="-11"><a class="markdownIt-Anchor" href="#-11"></a> <a href="#Return%E8%BF%94%E5%9B%9E%E6%B6%88%E6%81%AF" title="Return返回消息"></a>Return返回消息</h1>
<ul>
<li>Return Listener用于处理一些不可路由的消息</li>
<li>消息生产者通过指定一个<code>Exchange</code>和<code>RoutingKey</code>，把消息送达到某一个队列中去，然后消息监听者监听队列，进行消费处理操作</li>
<li>但是在某些情况下，如果我们在发送消息的时候，当前的<code>Exchange</code>不存在或者指定的路由key路由不到，这个时候如果我们需要监听这种不可达的消息，就要使用Return Listener</li>
<li><strong>Mandatory</strong>：如果为true，则监听器会接受到路由不可达的消息，然后进行后续处理，如果为false，那么broker端会自动删除该消息</li>
</ul>
<p><img src="https://fantasy-ke.github.io/picx-images-hosting/rabbitMQ/image.3yegwb5uo1.webp" alt="image.png" /></p>
<h2 id="-12"><a class="markdownIt-Anchor" href="#-12"></a> <a href="#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B-1" title="代码示例"></a>代码示例</h2>
<h3 id="-13"><a class="markdownIt-Anchor" href="#-13"></a> <a href="#%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE-1" title="创建项目"></a>创建项目</h3>
<p>创建两个控制台应用程序</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ReturnListenerSample.Consumer  </span><br><span class="line">ReturnListenerSample.Producer  </span><br></pre></td></tr></table></figure>
<p>再分别通过nuget引入<code>RabbitMQ.Client</code></p>
<h3 id="-14"><a class="markdownIt-Anchor" href="#-14"></a> <a href="#%E5%85%B7%E4%BD%93%E4%BB%A3%E7%A0%81-1" title="具体代码"></a>具体代码</h3>
<p>ReturnListenerSample.Producer</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Text;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">ReturnListenerSample.Producer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">  <span class="keyword">class</span> <span class="title">Program</span>  </span><br><span class="line">  &#123;  </span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>\[\] args</span>)</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">      Console.WriteLine(<span class="string">&quot;\*\*\*\*\*\* Return Listener Producer \*\*\*\*\*\*&quot;</span>);  </span><br><span class="line">        </span><br><span class="line">      <span class="keyword">var</span> connectionFactory = <span class="keyword">new</span> ConnectionFactory()  </span><br><span class="line">      &#123;  </span><br><span class="line">        HostName = <span class="string">&quot;127.0.0.1&quot;</span>,  </span><br><span class="line">        Port = <span class="number">5672</span>,  </span><br><span class="line">        UserName = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">        Password = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">        VirtualHost = <span class="string">&quot;/&quot;</span>  </span><br><span class="line">      &#125;;  </span><br><span class="line">      <span class="keyword">using</span> <span class="keyword">var</span> connection = connectionFactory.CreateConnection();  </span><br><span class="line">      <span class="keyword">using</span> <span class="keyword">var</span> channel = connection.CreateModel();  </span><br><span class="line">        </span><br><span class="line">      <span class="keyword">var</span> exchangeName = <span class="string">&quot;return _listener _exchange&quot;</span>;  </span><br><span class="line">      <span class="keyword">var</span> routingKey = <span class="string">&quot;order.save&quot;</span>;  </span><br><span class="line">      <span class="keyword">var</span> routingKeyError = <span class="string">&quot;abc.save&quot;</span>;  </span><br><span class="line">        </span><br><span class="line">      <span class="keyword">var</span> message = <span class="string">&quot;Hello RabbitMQ For ReturnListener&quot;</span>;  </span><br><span class="line">      <span class="keyword">var</span> body = Encoding.UTF8.GetBytes(message);  </span><br><span class="line">        </span><br><span class="line">      channel.BasicPublish(exchangeName,routingKey,mandatory:<span class="literal">true</span>,<span class="literal">null</span>,body);  </span><br><span class="line">      channel.BasicPublish(exchangeName, routingKeyError, mandatory: <span class="literal">true</span>, <span class="literal">null</span>, body);  </span><br><span class="line">        </span><br><span class="line">      channel.BasicReturn += (model, ea) =&gt;  </span><br><span class="line">      &#123;  </span><br><span class="line">        Console.WriteLine(<span class="string">&quot;---------- 消息发送失败 ----------&quot;</span>);  </span><br><span class="line">        Console.WriteLine(<span class="string">$&quot;ReplyCode = <span class="subst">&#123;ea.ReplyCode&#125;</span>&quot;</span>);  </span><br><span class="line">        Console.WriteLine(<span class="string">$&quot;ReplyText =<span class="subst">&#123;ea.ReplyText&#125;</span>&quot;</span>);  </span><br><span class="line">        Console.WriteLine(<span class="string">$&quot;Exchange = <span class="subst">&#123;ea.Exchange&#125;</span>&quot;</span>);  </span><br><span class="line">        Console.WriteLine(<span class="string">$&quot;RoutingKey = <span class="subst">&#123;ea.RoutingKey&#125;</span>&quot;</span>);  </span><br><span class="line">      &#125;;  </span><br><span class="line">        </span><br><span class="line">      Console.WriteLine(<span class="string">&quot;消息发送完成&quot;</span>);  </span><br><span class="line">      Console.WriteLine(<span class="string">&quot;输入回车退出...&quot;</span>);  </span><br><span class="line">      Console.ReadLine();  </span><br><span class="line">      </span><br><span class="line">    &#125;  </span><br><span class="line">  &#125;  </span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<p>ReturnListenerSample.Consumer</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Text;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client.Events;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">ReturnListenerSample.Consumer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">class</span> <span class="title">Program</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>\[\] args</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;\*\*\*\*\*\* Return Listener Consumer \*\*\*\*\*\*&quot;</span>);  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> connectionFactory = <span class="keyword">new</span> ConnectionFactory()  </span><br><span class="line">            &#123;  </span><br><span class="line">                HostName = <span class="string">&quot;127.0.0.1&quot;</span>,  </span><br><span class="line">                Port = <span class="number">5672</span>,  </span><br><span class="line">                UserName = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                Password = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                VirtualHost = <span class="string">&quot;/&quot;</span>  </span><br><span class="line">            &#125;;  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> connection = connectionFactory.CreateConnection();  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> channel = connection.CreateModel();  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> exchangeName = <span class="string">&quot;return _listener _exchange&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> routingKey = <span class="string">&quot;order.#&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> queueName = <span class="string">&quot;return _listener _queue&quot;</span>;  </span><br><span class="line">  </span><br><span class="line">            channel.ExchangeDeclare(exchangeName,ExchangeType.Topic,<span class="literal">true</span>,<span class="literal">false</span>,<span class="literal">null</span>);  </span><br><span class="line">            channel.QueueDeclare(queueName, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);  </span><br><span class="line">            channel.QueueBind(queueName,exchangeName,routingKey,<span class="literal">null</span>);  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> consumer = <span class="keyword">new</span> EventingBasicConsumer(channel);  </span><br><span class="line">            channel.BasicConsume(queueName, <span class="literal">true</span>, consumer);  </span><br><span class="line">            consumer.Received += (model, ea) =&gt;  </span><br><span class="line">            &#123;  </span><br><span class="line">                <span class="keyword">var</span> body = ea.Body;  </span><br><span class="line">                <span class="keyword">var</span> message = Encoding.UTF8.GetString(body.ToArray());  </span><br><span class="line">                Console.WriteLine(<span class="string">$&quot;接收到消息  <span class="subst">&#123;message&#125;</span>&quot;</span>);  </span><br><span class="line">            &#125;;  </span><br><span class="line">  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;输入回车退出...&quot;</span>);  </span><br><span class="line">            Console.ReadLine();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="-15"><a class="markdownIt-Anchor" href="#-15"></a> <a href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B6%88%E8%B4%B9%E8%80%85" title="自定义消费者"></a>自定义消费者</h1>
<p>自定义Consumer在日常工作中更常用，主要就是继承<code>DefaultBasicConsumer</code>这个类，然后<code>override HandleBasicDeliver()</code>这个方法即可</p>
<h2 id="-16"><a class="markdownIt-Anchor" href="#-16"></a> <a href="#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B-2" title="代码示例"></a>代码示例</h2>
<h3 id="-17"><a class="markdownIt-Anchor" href="#-17"></a> <a href="#%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE-2" title="创建项目"></a>创建项目</h3>
<p>创建两个控制台应用程序</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">CustomerConsumer.Consumer  </span><br><span class="line">CustomerConsumer.Producer  </span><br></pre></td></tr></table></figure>
<p>再分别通过nuget引入<code>RabbitMQ.Client</code></p>
<p>在<code>CustomerConsumer.Consumer</code>中创建类<code>MyConsumer.cs</code></p>
<h3 id="-18"><a class="markdownIt-Anchor" href="#-18"></a> <a href="#%E5%85%B7%E4%BD%93%E4%BB%A3%E7%A0%81-2" title="具体代码"></a>具体代码</h3>
<p>CustomerConsumer.Producer.Program.cs</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Text;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">CustomerConsumer.Producer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">class</span> <span class="title">Program</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>\[\] args</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;\*\*\*\*\*\* Customer Consumer Producer \*\*\*\*\*\*&quot;</span>);  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> connectionFactory = <span class="keyword">new</span> ConnectionFactory()  </span><br><span class="line">            &#123;  </span><br><span class="line">                HostName = <span class="string">&quot;127.0.0.1&quot;</span>,  </span><br><span class="line">                Port = <span class="number">5672</span>,  </span><br><span class="line">                UserName = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                Password = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                VirtualHost = <span class="string">&quot;/&quot;</span>  </span><br><span class="line">            &#125;;  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> connection = connectionFactory.CreateConnection();  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> channel = connection.CreateModel();  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> exchangeName = <span class="string">&quot;customer _consumer _exchange&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> routingKey = <span class="string">&quot;customer.save&quot;</span>;  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> message = <span class="string">&quot;Hello RabbitMQ For Customer _Consumer&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> body = Encoding.UTF8.GetBytes(message);  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">for</span> (<span class="built_in">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++)  </span><br><span class="line">            &#123;  </span><br><span class="line">                channel.BasicPublish(exchangeName, routingKey, <span class="literal">true</span>, <span class="literal">null</span>, body);  </span><br><span class="line">            &#125;  </span><br><span class="line">   </span><br><span class="line">  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;消息发送完成&quot;</span>);  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>CustomerConsumer.Consumer.MyConsumer.cs</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Text;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">CustomerConsumer.Consumer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">MyConsumer</span> : <span class="title">DefaultBasicConsumer</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">readonly</span> IModel  _model;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">MyConsumer</span>(<span class="params">IModel model</span>):<span class="title">base</span>(<span class="params">model</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            _model = model;  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">HandleBasicDeliver</span>(<span class="params"><span class="built_in">string</span> consumerTag, <span class="built_in">ulong</span> deliveryTag, <span class="built_in">bool</span> redelivered, <span class="built_in">string</span> exchange, <span class="built_in">string</span> routingKey,  </span></span></span><br><span class="line"><span class="params"><span class="function">            IBasicProperties properties, ReadOnlyMemory&lt;<span class="built_in">byte</span>&gt; body</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;consumerTag = <span class="subst">&#123;consumerTag&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;deliveryTag = <span class="subst">&#123;deliveryTag&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;redelivered = <span class="subst">&#123;redelivered&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;exchange = <span class="subst">&#123;exchange&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;routingKey = <span class="subst">&#123;routingKey&#125;</span>&quot;</span>);  </span><br><span class="line">            <span class="keyword">var</span> message = Encoding.UTF8.GetString(body.ToArray());  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;Message = <span class="subst">&#123;message&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;===========================================&quot;</span>);  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>CustomerConsumer.Consumer.Program.cs</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">CustomerConsumer.Consumer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">class</span> <span class="title">Program</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>[] args</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;\*\*\*\*\*\* Customer Consumer Producer \*\*\*\*\*\*&quot;</span>);  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> connectionFactory = <span class="keyword">new</span> ConnectionFactory()  </span><br><span class="line">            &#123;  </span><br><span class="line">                HostName = <span class="string">&quot;127.0.0.1&quot;</span>,  </span><br><span class="line">                Port = <span class="number">5672</span>,  </span><br><span class="line">                UserName = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                Password = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                VirtualHost = <span class="string">&quot;/&quot;</span>  </span><br><span class="line">            &#125;;  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> connection = connectionFactory.CreateConnection();  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> channel = connection.CreateModel();  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> exchangeName = <span class="string">&quot;customer _consumer _exchange&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> routingKey = <span class="string">&quot;customer.#&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> queueName = <span class="string">&quot;customer _consumer _queue&quot;</span>;  </span><br><span class="line">  </span><br><span class="line">            channel.ExchangeDeclare(exchangeName,ExchangeType.Topic,<span class="literal">true</span>,<span class="literal">false</span>,<span class="literal">null</span>);  </span><br><span class="line">            channel.QueueDeclare(queueName, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);  </span><br><span class="line">            channel.QueueBind(queueName, exchangeName, routingKey);  </span><br><span class="line">  </span><br><span class="line">            channel.BasicConsume(queueName, <span class="literal">true</span>, <span class="keyword">new</span> MyConsumer(channel));  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;输入回车退出...&quot;</span>);  </span><br><span class="line">            Console.ReadLine();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="-19"><a class="markdownIt-Anchor" href="#-19"></a> <a href="#%E6%B6%88%E6%81%AF%E7%9A%84%E9%99%90%E6%B5%81" title="消息的限流"></a>消息的限流</h1>
<p>为什么需要消费端限流：当消费端处理能力达不到生产端的生产速度，或当Broker中囤积了巨量消息，当消费端启动之后，巨量消息同一时间全部推送到消费端，会直接导致消费端崩溃，</p>
<p>RabbitMQ提供了一种Qos(服务质量保证)功能，即在非自动确认消息的前提下，如果一定数目的消息(通过基于consumer或者channel设置Qos的值)未被确认之前，不进行消费新的消息</p>
<p>主要操作方式就是调用<code>channel</code>上的<code>BasicQos</code>方法设置，其中参数意思如下：</p>
<ul>
<li>
<p>prefetchSize：表示单挑消息的最大限制，一般设置为0表示对单挑消息的体积大小不做限制</p>
</li>
<li>
<p>prefetchCount：表示Broker最多同时给一个消费者推送多少条消息，一旦有这么多条消息没有ack，则该consumer将block掉，知道有消息ack，Broker才会继续推消息</p>
</li>
<li>
<p>global：true/false，是否将上面的设置应用于channel，简单点说就是上面限制是channel级别还是consumer级别</p>
</li>
<li>
<p><em>注意：这里的设置一定是在调用channel.BasicConsume()的时候设置consumer的autoAck=false才有效，并且一般开发中都是将autoAck设置为false，然后在业务逻辑处理完之后再手动ack*</em></p>
</li>
</ul>
<h2 id="-20"><a class="markdownIt-Anchor" href="#-20"></a> <a href="#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B-3" title="代码示例"></a>代码示例</h2>
<h3 id="-21"><a class="markdownIt-Anchor" href="#-21"></a> <a href="#%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE-3" title="创建项目"></a>创建项目</h3>
<p>创建两个控制台应用程序</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ConsumerLimit.Consumer  </span><br><span class="line">ConsumerLimit.Producer  </span><br></pre></td></tr></table></figure>
<p>再分别通过nuget引入<code>RabbitMQ.Client</code></p>
<p>在<code>ConsumerLimit.Consumer</code>中创建类<code>MyConsumer.cs</code></p>
<h4 id="-22"><a class="markdownIt-Anchor" href="#-22"></a> <a href="#%E5%85%B7%E4%BD%93%E4%BB%A3%E7%A0%81-3" title="具体代码"></a>具体代码</h4>
<p>ConsumerLimit.Producer.Program</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Text;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">ConsumerLimit.Producer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">class</span> <span class="title">Program</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>[] args</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;\*\*\*\*\*\*\*\*\*\* Consumer Limit Producer \*\*\*\*\*\*\*\*\*\*&quot;</span>);  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> connectionFactory = <span class="keyword">new</span> ConnectionFactory()  </span><br><span class="line">            &#123;  </span><br><span class="line">                HostName = <span class="string">&quot;127.0.0.1&quot;</span>,  </span><br><span class="line">                Port = <span class="number">5672</span>,  </span><br><span class="line">                UserName = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                Password = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                VirtualHost = <span class="string">&quot;/&quot;</span>  </span><br><span class="line">            &#125;;  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> connection = connectionFactory.CreateConnection();  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> channel = connection.CreateModel();  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> exchangeName = <span class="string">&quot;consumer _limit _exchange&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> routingKey = <span class="string">&quot;order.saved&quot;</span>;  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> random = <span class="keyword">new</span> Random();  </span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++)  </span><br><span class="line">            &#123;  </span><br><span class="line">                <span class="keyword">var</span> message = <span class="string">$&quot;Hello RabbitMQ For Consumer Limit <span class="subst">&#123;random.Next(<span class="number">1</span>,<span class="number">100</span>)&#125;</span>&quot;</span>;  </span><br><span class="line">                <span class="keyword">var</span> body = Encoding.UTF8.GetBytes(message);  </span><br><span class="line">                channel.BasicPublish(exchangeName, routingKey, <span class="literal">null</span>, body);  </span><br><span class="line">            &#125;  </span><br><span class="line">  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;消息发送完成&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;输入回车退出...&quot;</span>);  </span><br><span class="line">            Console.ReadLine();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ConsumerLimit.Consumer.MyConsumer</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Collections.Generic;  </span><br><span class="line"><span class="keyword">using</span> System.Text;  </span><br><span class="line"><span class="keyword">using</span> System.Threading;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">ConsumerLimit.Consumer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">MyConsumer</span>:<span class="title">DefaultBasicConsumer</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">readonly</span> IModel  _channel;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">MyConsumer</span>(<span class="params">IModel channel</span>):<span class="title">base</span>(<span class="params">channel</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            _channel = channel;  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">HandleBasicDeliver</span>(<span class="params"><span class="built_in">string</span> consumerTag, <span class="built_in">ulong</span> deliveryTag, <span class="built_in">bool</span> redelivered, <span class="built_in">string</span> exchange, <span class="built_in">string</span> routingKey,  </span></span></span><br><span class="line"><span class="params"><span class="function">            IBasicProperties properties, ReadOnlyMemory&lt;<span class="built_in">byte</span>&gt; body</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            Console.WriteLine();  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;====================&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;接收到消息：<span class="subst">&#123;Encoding.UTF8.GetString(body.ToArray())&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;consumerTag = <span class="subst">&#123;consumerTag&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;deliveryTag = <span class="subst">&#123;deliveryTag&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;redelivered = <span class="subst">&#123;redelivered&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;exchange = <span class="subst">&#123;exchange&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;routingKey = <span class="subst">&#123;routingKey&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;正在模拟业务操作...&quot;</span>);  </span><br><span class="line">            Thread.Sleep(<span class="number">2000</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;业务处理完毕&quot;</span>);  </span><br><span class="line">            _channel.BasicAck(deliveryTag,<span class="literal">false</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;====================&quot;</span>);  </span><br><span class="line">            Console.WriteLine();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ConsumerLimit.Consumer.Program</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Text;  </span><br><span class="line"><span class="keyword">using</span> System.Threading;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client.Events;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">ConsumerLimit.Consumer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">class</span> <span class="title">Program</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>[] args</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;\*\*\*\*\*\*\*\*\*\* Consumer Limit Consumer \*\*\*\*\*\*\*\*\*\*&quot;</span>);  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> connectionFactory = <span class="keyword">new</span> ConnectionFactory()  </span><br><span class="line">            &#123;  </span><br><span class="line">                HostName = <span class="string">&quot;127.0.0.1&quot;</span>,  </span><br><span class="line">                Port = <span class="number">5672</span>,  </span><br><span class="line">                UserName = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                Password = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                VirtualHost = <span class="string">&quot;/&quot;</span>  </span><br><span class="line">            &#125;;  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> connection = connectionFactory.CreateConnection();  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> channel = connection.CreateModel();  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> exchangeName = <span class="string">&quot;consumer _limit _exchange&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> routingKey = <span class="string">&quot;order.#&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> queueName = <span class="string">&quot;consumer _limit _queue&quot;</span>;  </span><br><span class="line">  </span><br><span class="line">            channel.ExchangeDeclare(exchangeName, ExchangeType.Topic, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">null</span>);  </span><br><span class="line">            channel.QueueDeclare(queueName, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);  </span><br><span class="line">            channel.QueueBind(queueName, exchangeName, routingKey, <span class="literal">null</span>);  </span><br><span class="line">  </span><br><span class="line">            channel.BasicConsume(queueName, <span class="literal">false</span>, <span class="keyword">new</span> MyConsumer(channel));  </span><br><span class="line">            channel.BasicQos(prefetchSize:<span class="number">0</span>,prefetchCount:<span class="number">1</span>,<span class="keyword">global</span>:<span class="literal">false</span>);  </span><br><span class="line">  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;输入回车退出...&quot;</span>);  </span><br><span class="line">            Console.ReadLine();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="-23"><a class="markdownIt-Anchor" href="#-23"></a> <a href="#%E6%B6%88%E6%81%AF%E7%9A%84ACK%E4%B8%8E%E9%87%8D%E5%9B%9E%E9%98%9F%E5%88%97" title="消息的ACK与重回队列"></a>消息的ACK与重回队列</h1>
<h2 id="-24"><a class="markdownIt-Anchor" href="#-24"></a> <a href="#%E6%B6%88%E8%B4%B9%E7%AB%AF%E7%9A%84%E6%89%8B%E5%B7%A5ACK%E5%92%8CNACK" title="消费端的手工ACK和NACK"></a>消费端的手工ACK和NACK</h2>
<ul>
<li>ACK=消息已经成功处理了</li>
<li>NACK=消息我处理失败了(Broker会进行重新投递)</li>
</ul>
<p>使用场景：</p>
<ul>
<li>消费端进行消费的时候，如果由于业务异常可以进行NACK，当尝试到足够的次数都一直处理失败，则返回记录日志后续做补偿，然后返回ACK</li>
<li>由于服务器宕机等严重问题，Broker即没收到ACK也没有收到NACK，那么Broker也会进行重新推送消息，这时如果处理完消息，返回ACK可以保障Broker知道消费端已经成功消费</li>
</ul>
<h2 id="-25"><a class="markdownIt-Anchor" href="#-25"></a> <a href="#%E6%B6%88%E8%B4%B9%E7%AB%AF%E7%9A%84%E9%87%8D%E5%9B%9E%E9%98%9F%E5%88%97" title="消费端的重回队列"></a>消费端的重回队列</h2>
<ul>
<li>消费端重回队列是为了对没有处理成功的消息，把消息重新会递给Broker</li>
<li>一般在实际应用中，都会关闭重回队列，也就是设置为False</li>
</ul>
<h2 id="-26"><a class="markdownIt-Anchor" href="#-26"></a> <a href="#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B-4" title="代码示例"></a>代码示例</h2>
<h3 id="-27"><a class="markdownIt-Anchor" href="#-27"></a> <a href="#%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE-4" title="创建项目"></a>创建项目</h3>
<p>创建两个控制台应用程序</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">AckSample.Consumer  </span><br><span class="line">AckSample.Producer  </span><br><span class="line">``</span><br><span class="line">再分别通过nuget引入`RabbitMQ.Client`</span><br><span class="line"></span><br><span class="line">在`AckSample.Consumer`中创建类`MyConsumer.cs`</span><br><span class="line"></span><br><span class="line"><span class="meta">### [](#具体代码-4 &quot;具体代码&quot;)具体代码</span></span><br><span class="line"></span><br><span class="line">AckSample.Producer.Program</span><br><span class="line"></span><br><span class="line">```csharp</span><br><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Collections.Generic;  </span><br><span class="line"><span class="keyword">using</span> System.Text;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">AckSample.Producer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">class</span> <span class="title">Program</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>[] args</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;\*\*\*\*\*\*\*\*\*\* ACK Sample Producer \*\*\*\*\*\*\*\*\*\*&quot;</span>);  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> connectionFactory = <span class="keyword">new</span> ConnectionFactory()  </span><br><span class="line">            &#123;  </span><br><span class="line">                HostName = <span class="string">&quot;127.0.0.1&quot;</span>,  </span><br><span class="line">                Port = <span class="number">5672</span>,  </span><br><span class="line">                UserName = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                Password = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                VirtualHost = <span class="string">&quot;/&quot;</span>  </span><br><span class="line">            &#125;;  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> connection = connectionFactory.CreateConnection();  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> channel = connection.CreateModel();  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> exchangeName = <span class="string">&quot;ack _sample _exchange&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> routingKey = <span class="string">&quot;order.saved&quot;</span>;  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> random =<span class="keyword">new</span> Random();  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++)  </span><br><span class="line">            &#123;  </span><br><span class="line">                <span class="keyword">var</span> properties = channel.CreateBasicProperties();  </span><br><span class="line">                properties.DeliveryMode = <span class="number">2</span>;  </span><br><span class="line">                properties.ContentEncoding = <span class="string">&quot;UTF-8&quot;</span>;  </span><br><span class="line">                properties.Headers = <span class="keyword">new</span> Dictionary&lt;<span class="built_in">string</span>, <span class="built_in">object</span>&gt;() &#123;&#123;<span class="string">&quot;num&quot;</span>, random.Next(<span class="number">0</span>, <span class="number">10</span>).ToString()&#125;&#125;;  </span><br><span class="line">  </span><br><span class="line">                <span class="keyword">var</span> message = <span class="string">$&quot;Hello RabbitMQ For ACK  -&gt;  <span class="subst">&#123;i&#125;</span>&quot;</span>;  </span><br><span class="line">                <span class="keyword">var</span> body = Encoding.UTF8.GetBytes(message);  </span><br><span class="line">  </span><br><span class="line">                channel.BasicPublish(exchangeName, routingKey, properties, body);  </span><br><span class="line">            &#125;  </span><br><span class="line">  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;输入回车退出...&quot;</span>);  </span><br><span class="line">            Console.ReadLine();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>AckSample.Consumer.MyConsumer</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Collections.Generic;  </span><br><span class="line"><span class="keyword">using</span> System.Text;  </span><br><span class="line"><span class="keyword">using</span> System.Threading;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line"><span class="keyword">using</span> Console = System.Console;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">AckSample.Consumer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">MyConsumer</span>:<span class="title">DefaultBasicConsumer</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">readonly</span> IModel _channel;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">MyConsumer</span>(<span class="params">IModel channel</span>):<span class="title">base</span>(<span class="params">channel</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            _channel = channel;  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">HandleBasicDeliver</span>(<span class="params"><span class="built_in">string</span> consumerTag, <span class="built_in">ulong</span> deliveryTag, <span class="built_in">bool</span> redelivered, <span class="built_in">string</span> exchange, <span class="built_in">string</span> routingKey,  </span></span></span><br><span class="line"><span class="params"><span class="function">            IBasicProperties properties, ReadOnlyMemory&lt;<span class="built_in">byte</span>&gt; body</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            Console.WriteLine();  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;====================&quot;</span>);  </span><br><span class="line">            <span class="keyword">var</span> stringNum = properties.Headers[<span class="string">&quot;num&quot;</span>];  </span><br><span class="line">            <span class="keyword">var</span> byteNum = stringNum <span class="keyword">as</span> <span class="built_in">byte</span>[];  </span><br><span class="line">            Console.WriteLine(<span class="string">$&quot;接收到消息  num=<span class="subst">&#123;Encoding.UTF8.GetString(byteNum)&#125;</span>  <span class="subst">&#123;Encoding.UTF8.GetString(body.ToArray())&#125;</span>&quot;</span>);  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;......模拟业务操作......&quot;</span>);  </span><br><span class="line">            <span class="keyword">var</span> num = <span class="built_in">int</span>.Parse(Encoding.UTF8.GetString(byteNum));  </span><br><span class="line">            <span class="keyword">if</span> (num % <span class="number">2</span> == <span class="number">0</span>)  </span><br><span class="line">            &#123;  </span><br><span class="line">                Console.WriteLine(<span class="string">&quot;......业务处理失败......&quot;</span>);  </span><br><span class="line">                _channel.BasicNack(deliveryTag, <span class="literal">false</span>, <span class="literal">true</span>);  </span><br><span class="line">            &#125;  </span><br><span class="line">            <span class="keyword">else</span>  </span><br><span class="line">            &#123;  </span><br><span class="line">                Console.WriteLine(<span class="string">&quot;......业务处理成功......&quot;</span>);  </span><br><span class="line">                _channel.BasicAck(deliveryTag,<span class="literal">false</span>);  </span><br><span class="line">            &#125;  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;====================&quot;</span>);  </span><br><span class="line">            Console.WriteLine();  </span><br><span class="line">            Thread.Sleep(<span class="number">2000</span>);  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br><span class="line">```   </span><br><span class="line">AckSample.Consumer.Program</span><br><span class="line">```csharp</span><br><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">namespace</span> <span class="title">AckSample.Consumer</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">class</span> <span class="title">Program</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>[] args</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;\*\*\*\*\*\*\*\*\*\* ACK Sample Consumer \*\*\*\*\*\*\*\*\*\*&quot;</span>);  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> connectionFactory = <span class="keyword">new</span> ConnectionFactory()  </span><br><span class="line">            &#123;  </span><br><span class="line">                HostName = <span class="string">&quot;127.0.0.1&quot;</span>,  </span><br><span class="line">                Port = <span class="number">5672</span>,  </span><br><span class="line">                UserName = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                Password = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                VirtualHost = <span class="string">&quot;/&quot;</span>  </span><br><span class="line">            &#125;;  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> connection = connectionFactory.CreateConnection();  </span><br><span class="line">            <span class="keyword">using</span> <span class="keyword">var</span> channel = connection.CreateModel();  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> exchangeName = <span class="string">&quot;ack _sample _exchange&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> queueName = <span class="string">&quot;ack _sample _queue&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> routingKey = <span class="string">&quot;order.saved&quot;</span>;  </span><br><span class="line">  </span><br><span class="line">            channel.ExchangeDeclare(exchangeName, ExchangeType.Topic, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">null</span>);  </span><br><span class="line">            channel.QueueDeclare(queueName, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);  </span><br><span class="line">            channel.QueueBind(queueName,exchangeName,routingKey);  </span><br><span class="line">  </span><br><span class="line">            channel.BasicConsume(queueName, <span class="literal">false</span>, <span class="keyword">new</span> MyConsumer(channel));  </span><br><span class="line">  </span><br><span class="line">            Console.WriteLine(<span class="string">&quot;输入回车退出...&quot;</span>);  </span><br><span class="line">            Console.ReadLine();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="-28"><a class="markdownIt-Anchor" href="#-28"></a> <a href="#TTL%E6%B6%88%E6%81%AF" title="TTL消息"></a>TTL消息</h1>
<p>主要就是两点，TTL可以针对消息本身也可以针对消息队列</p>
<p>消息本身通过消息的<code>Properties</code>中设置<code>Expiration</code>属性来设置过期时间</p>
<p>Queue通过声明的时候在<code>arguments</code>字典参数里添加<code>x-message-ttl</code>这个键值对来设置进入该消息队列的消息有效期</p>
<h1 id="-29"><a class="markdownIt-Anchor" href="#-29"></a> <a href="#DLX%E2%80%93%E6%AD%BB%E4%BF%A1%E9%98%9F%E5%88%97-Dead-Letter-Exchange" title="DLX–死信队列(Dead-Letter-Exchange)"></a>DLX–死信队列(Dead-Letter-Exchange)</h1>
<p>利用DLX，当消息在一个队列变成死信(dead message)之后，它能被重新publish到另一个Exchange，这个Exchange就是DLX</p>
<p>消息编程死信的情况：</p>
<ul>
<li>消息被拒绝(basic.reject/basic.nack)，并且requeue=false(不再重回队列)</li>
<li>消息TTL过期</li>
<li>队列达到最大长度</li>
</ul>
<p>死信队列</p>
<ul>
<li>DLX也是一个正常的Exchange，和一般的Exchange没有区别，它能在仍和的队列上被指定，实际上就是设置某个队列的属性</li>
<li>当这个队列中有死信时，RabbitMQ就会自动的将这个消息重新发布到设置的Exchange上去，进而被路由到另一个队列</li>
<li>可以监听这个队列中消息做相应的处理，这个特性可以弥补RabbitMQ以前支持的immediate参数的功能</li>
</ul>
<p>死信队列设置：</p>
<ul>
<li>首先需要设置死信队列的exchange和queue，然后进行绑定
<ul>
<li>Exchange：dlx.exchange</li>
<li>Queue：dlx.queue</li>
<li>RoutingKey：#</li>
</ul>
</li>
<li>然后进行正常声明交换机、队列、绑定，只不过需要在队列上的arguments字典上加一个键值对：<code>x-dead-letter-exchange:dlx.exchange</code></li>
</ul>
<h1 id="-30"><a class="markdownIt-Anchor" href="#-30"></a> <a href="#ASP-NET-Core%E5%81%9A%E6%B6%88%E8%B4%B9%E8%80%85" title="ASP.NET Core做消费者"></a><span class="exturl" data-url="aHR0cDovL0FTUC5ORVQ=">ASP.NET<i class="fa fa-external-link-alt"></i></span> Core做消费者</h1>
<p>主要思路：创建一个<code>HostedService</code>服务类，继承<code>BackgroundService</code>，<code>override ExecuteAsync</code>方法，然后在里面做消息监听，最后在<code>Startup.ConfigureServices</code>中注册这个<code>HostedService</code></p>
<h2 id="-31"><a class="markdownIt-Anchor" href="#-31"></a> <a href="#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B-5" title="代码示例"></a>代码示例</h2>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;  </span><br><span class="line"><span class="keyword">using</span> System.Collections.Generic;  </span><br><span class="line"><span class="keyword">using</span> System.Linq;  </span><br><span class="line"><span class="keyword">using</span> System.Threading;  </span><br><span class="line"><span class="keyword">using</span> System.Threading.Tasks;  </span><br><span class="line"><span class="keyword">using</span> Microsoft.Extensions.Hosting;  </span><br><span class="line"><span class="keyword">using</span> Microsoft.Extensions.Logging;  </span><br><span class="line"><span class="keyword">using</span> RabbitMQ.Client;  </span><br><span class="line"><span class="keyword">using</span> WebSiteConsumerSample.Consumers;  </span><br><span class="line">  </span><br><span class="line"><span class="comment">// ReSharper disable UnusedMember.Global  </span></span><br><span class="line"><span class="comment">// ReSharper disable InconsistentNaming  </span></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">WebSiteConsumerSample.BackgroundServices</span>  </span><br><span class="line">&#123;  </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">ConsumeRabbitMQHostedService</span> : <span class="title">BackgroundService</span>  </span><br><span class="line">    &#123;  </span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">readonly</span> ILogger&lt;ConsumeRabbitMQHostedService&gt;  _logger;  </span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">readonly</span> ILogger&lt;SolutionMessageConsumer&gt;  _consumerLogger;  </span><br><span class="line">        <span class="keyword">private</span> IConnection  _connection;  </span><br><span class="line">        <span class="keyword">private</span> IModel  _channel;  </span><br><span class="line">  </span><br><span class="line">        <span class="keyword">private</span> <span class="built_in">string</span>  _exchangeName;  </span><br><span class="line">        <span class="keyword">private</span> <span class="built_in">string</span>  _queueName;  </span><br><span class="line">        <span class="keyword">private</span> <span class="built_in">string</span>  _routingKey;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">ConsumeRabbitMQHostedService</span>(<span class="params">ILogger&lt;ConsumeRabbitMQHostedService&gt; logger,ILogger&lt;SolutionMessageConsumer&gt; consumerLogger</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            _logger = logger;  </span><br><span class="line">            _consumerLogger = consumerLogger;  </span><br><span class="line">            InitRabbitMq();  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">InitRabbitMq</span>()</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            <span class="keyword">var</span> connectionFactory = <span class="keyword">new</span> ConnectionFactory()  </span><br><span class="line">            &#123;  </span><br><span class="line">                HostName = <span class="string">&quot;127.0.0.1&quot;</span>,  </span><br><span class="line">                Port = <span class="number">5672</span>,  </span><br><span class="line">                UserName = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                Password = <span class="string">&quot;admin&quot;</span>,  </span><br><span class="line">                VirtualHost = <span class="string">&quot;/&quot;</span>  </span><br><span class="line">            &#125;;  </span><br><span class="line">  </span><br><span class="line">            _connection = connectionFactory.CreateConnection();  </span><br><span class="line">            _channel =  _connection.CreateModel();  </span><br><span class="line">  </span><br><span class="line">            <span class="keyword">var</span> exchangeName = <span class="string">&quot;dimsum _solution _exchange&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> queueName = <span class="string">&quot;dimsum _solution _queue&quot;</span>;  </span><br><span class="line">            <span class="keyword">var</span> routingKey = <span class="string">&quot;solution.#&quot;</span>;  </span><br><span class="line">  </span><br><span class="line">            _exchangeName = exchangeName;  </span><br><span class="line">            _queueName = queueName;  </span><br><span class="line">            _routingKey = routingKey;  </span><br><span class="line">  </span><br><span class="line">            _channel.ExchangeDeclare(exchangeName, ExchangeType.Topic, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">null</span>);  </span><br><span class="line">            _channel.QueueDeclare(queueName, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);  </span><br><span class="line">            _channel.QueueBind(queueName, exchangeName, routingKey, <span class="literal">null</span>);  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">protected</span> <span class="keyword">override</span> <span class="keyword">async</span> Task <span class="title">ExecuteAsync</span>(<span class="params">CancellationToken stoppingToken</span>)</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            <span class="keyword">await</span> Task.CompletedTask;  </span><br><span class="line">            stoppingToken.ThrowIfCancellationRequested();  </span><br><span class="line">            _channel.BasicConsume( _queueName, <span class="literal">false</span>, <span class="keyword">new</span> SolutionMessageConsumer( _channel,  _consumerLogger));  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">Dispose</span>()</span>  </span><br><span class="line">        &#123;  </span><br><span class="line">            _channel.Dispose();  </span><br><span class="line">            _connection.Dispose();  </span><br><span class="line">            <span class="keyword">base</span>.Dispose();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<p>在<code>Startup.ConfigureServices</code>中添加</p>
<p>1</p>
<p>services.AddHostedService<ConsumeRabbitMQHostedService>();</p>

    </div>

    
    
    

    <footer class="post-footer">







<div class="license">
  <div class="license-title">RabbitMQ进阶</div>
  <div class="license-link">
    <a href="https://blog.fantasyke.cn/posts/59211/">https://blog.fantasyke.cn/posts/59211/</a>
  </div>
  <div class="license-meta">
    <div class="license-meta-item">
      <div class="license-meta-title">本文作者</div>
      <div class="license-meta-text">
          Fantasy-ke
      </div>
    </div>
      <div class="license-meta-item">
        <div class="license-meta-title">发布于</div>
        <div class="license-meta-text">
          2023-05-29
        </div>
      </div>
      <div class="license-meta-item">
        <div class="license-meta-title">更新于</div>
        <div class="license-meta-text">
          2024-12-17
        </div>
      </div>
    <div class="license-meta-item">
      <div class="license-meta-title">许可协议</div>
      <div class="license-meta-text">
          禁止转载引用
      </div>
    </div>
  </div>
  <div class="license-statement">
      如需转载或引用本文，请先获得作者授权！
  </div>
</div>
          <div class="reward-container">
  <div>Buy me a coffee</div>
  <button>
    Donate
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechatpay.png" alt="Fantasy-ke WeChat Pay">
        <span>WeChat Pay</span>
      </div>

  </div>
</div>

          <div class="followme">
  <span>Welcome to my other publishing channels</span>

  <div class="social-list">

      <div class="social-item">
          <a target="_blank" class="social-link" href="https://github.com/fantasy-ke">
            <span class="icon">
              <i class="fab fa-github"></i>
            </span>

            <span class="label">GitHub</span>
          </a>
      </div>
  </div>
</div>

          <div class="post-tags">
              <a href="/tags/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/" rel="tag"><i class="fa fa-tag"></i> 消息队列</a>
              <a href="/tags/RabbitMQ/" rel="tag"><i class="fa fa-tag"></i> RabbitMQ</a>
          </div>

        
  <div class="social-like a2a_kit a2a_kit_size_32 a2a_default_style">
    <a class="a2a_dd" target="_blank" rel="noopener" href="https://www.addtoany.com/share"></a>
      <a class="a2a_button_facebook"></a>
      <a class="a2a_button_twitter"></a>
      <a class="a2a_button_telegram"></a>
      <a class="a2a_button_wechat"></a>
  </div>

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/posts/26216/" rel="prev" title="Redis基础">
                  <i class="fa fa-angle-left"></i> Redis基础
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/posts/33842/" rel="next" title="RabbitMQ基础">
                  RabbitMQ基础 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments gitalk-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2021 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-solid fa-t-rex"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Fantasy-ke</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>Word count total: </span>
    <span title="Word count total">72k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>Reading time total &asymp;</span>
    <span title="Reading time total">4:21</span>
  </span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="Total Visitors">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="Total Views">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div> 
<script src="https://cdn.jsdelivr.net/npm/moment@2.22.2/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment-precise-range-plugin@1.3.0/moment-precise-range.min.js"></script>
<script>
  var now = new Date();
  function timer() {
    var grt= new Date("03/12/2022 13:14:21");//此处修改你的建站时间或者网站上线时间
    now.setTime(now.getTime()+250);
    days = (now - grt ) / 1000 / 60 / 60 / 24; dnum = Math.floor(days);
    hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum); hnum = Math.floor(hours);
    if(String(hnum).length ==1 ){hnum = "0" + hnum;} minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
    mnum = Math.floor(minutes); if(String(mnum).length ==1 ){mnum = "0" + mnum;}
    seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
    snum = Math.round(seconds); if(String(snum).length ==1 ){snum = "0" + snum;}
    var ages = `${dnum}天${hnum}小时${mnum}分${snum}秒`;
    div.innerHTML = `本站已安全运行 ${ages} 🐶`;
  }
  var div = document.createElement("div");
  //插入到copyright之后
  var copyright = document.querySelector(".busuanzi-count");
  document.querySelector(".footer-inner").insertBefore(div, copyright.nextSibling);
  timer();
  setInterval("timer()",1000)
</script>


<div class="footer-menu">
    <a style="color: chocolate;" href="/tags/">文章标签</a> · <a style="color: chocolate;"  href="/policy/">网站政策</a> · <a style="color: chocolate;"  href="/photos/">文章相册</a>
</div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL2ZhbnRhc3kta2U=" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.31/fancybox/fancybox.umd.js" integrity="sha256-a+H7FYzJv6oU2hfsfDGM2Ohw/cR9v+hPfxHCLdmCrE8=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>


  <script src="/js/third-party/addtoany.js"></script>

  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




<script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.5.7/lib/darkmode-js.min.js"></script>

<script>
var options = {
  bottom: '64px',
  right: 'unset',
  left: '32px',
  time: '0.5s',
  mixColor: 'transparent',
  backgroundColor: 'transparent',
  buttonColorDark: '#100f2c',
  buttonColorLight: '#fff',
  saveInCookies: true,
  label: '🌓',
  autoMatchOsTheme: true
}
const darkmode = new Darkmode(options);
window.darkmode = darkmode;
darkmode.showWidget();
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.8.0/gitalk.css" integrity="sha256-AJnUHL7dBv6PGaeyPQJcgQPDjt/Hn/PvYZde1iqfp8U=" crossorigin="anonymous">

<script class="next-config" data-name="gitalk" type="application/json">{"enable":true,"github_id":"fantasy-ke","repo":"fantasy-ke.github.io","client_id":"Ov23li8eCFrhnzfiGx5T","client_secret":"ce23581c2059392ebd00afd08d5ba43f767fd1b1","admin_user":"fantasy-ke","distraction_free_mode":true,"proxy":"https://cors-anywhere.azm.workers.dev/https://github.com/login/oauth/access_token","language":"zh-CN","labels":"gitalk","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.8.0/gitalk.min.js","integrity":"sha256-MVK9MGD/XJaGyIghSVrONSnoXoGh3IFxLw0zfvzpxR4="},"path_md5":"d538d49b83276082e3ceee1c94987155"}</script>
<script src="/js/third-party/comments/gitalk.js"></script>


<script src="/js/minigrid.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script data-pjax type="text/javascript">
var album = document.querySelector(".album");
if (album) {
  // 相册列表 JSON 数据
  var imgDataPath = album.getAttribute('json-src');
  // 照片存储路径
  var imgPath = album.getAttribute('photo-src');
  // 最多显示数量
  var imgMaxNum = 50;
  // 获取窗口大小以决定图片宽度
  var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  var imageWidth;

  if (windowWidth < 768) {
    imageWidth = 145; // 移动端图片宽度
  } else {
    imageWidth = 235;
  }

  // 生成相册
  var linkDataPath = imgDataPath;
  var photo = {
    page: 1,
    offset: imgMaxNum,
    init: function () {
      var that = this;
      $.getJSON(linkDataPath, function (data) {
          that.render(that.page, data);
      });
    },
    render: function (page, data) {
      var begin = (page - 1) * this.offset;
      var end = page * this.offset;
      if (begin >= data.length) return;
      var imgNameWithPattern, imgName, imageSize, imageX, imageY, li = "";
      for (var i = begin; i < end && i < data.length; i++) {
        imgNameWithPattern = data[i].path;
        imgName = data[i].name;
        imageSize = data[i].size;
        li += '<div class="card" style="width:' + imageWidth + 'px" >';
        li += '<div class="album-photo" style="height:' + imageWidth + 'px" >';
        li += '<a class="fancybox fancybox.image" href="' + imgPath + imgNameWithPattern + '" itemscope="" itemtype="http://schema.org/ImageObject" itemprop="url" data-fancybox="group" rel="group" data-caption="' + imgName + '" title="' +  imgName + '">';
        li += '<img data-src="' + imgPath + imgNameWithPattern + '" src="' + imgPath + imgNameWithPattern + '" alt="' +  imgName + '" data-loaded="true">';
        li += '</a>';
        li += '</div>';
        li += '</div>';
      }
      album.insertAdjacentHTML('beforeend', li);
      this.minigrid();
    },
    minigrid: function () {
      var grid = new Minigrid({
        container: '.album',
        item: '.card',
        gutter: 12
      });
      grid.mount();
      window.addEventListener('resize', function () {
        grid.mount();
      });
    }
  };
  photo.init();
}
</script>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":170,"height":330},"mobile":{"show":true},"react":{"opacity":0.7},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
